<template>
  <div class="profit-chart-container">
    <div class="chart-header">
      <h3>年度收支分析</h3>
      <div class="year-selector">
        <span>选择年份范围：</span>
        <el-date-picker
            v-model="startY"
            type="year"
            placeholder="开始年份"
            value-format="yyyy"
            :picker-options="startPickerOptions">
        </el-date-picker>
        <span>至</span>
        <el-date-picker
            v-model="endY"
            type="year"
            placeholder="结束年份"
            :picker-options="endPickerOptions"
            value-format="yyyy"
            @change="fetchData"
        >
        </el-date-picker>
      </div>
    </div>

    <div class="chart-wrapper">
      <div ref="profitChart" class="profit-chart"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {getCostsListApi} from "@/api/costs";
import {getRevenueListApi} from "@/api/revenue";
require('echarts/theme/macarons') // 引入主题

export default {
  data() {
    const currentYear = new Date().getFullYear();

    return {
      startY:'2018',
      endY:'2025',
      startPickerOptions: {
        disabledDate: (time) => {
          // 开始年份不能小于2007年，不能大于结束年份
          return time.getFullYear() < 2007 ||
              (this.endY && time.getFullYear() > new Date(this.endY).getFullYear());
        }
      },
      endPickerOptions: {
        disabledDate: (time) => {
          // 结束年份不能小于2007年，不能小于开始年份，不能大于当前年
          return time.getFullYear() < 2007 ||
              (this.startY && time.getFullYear() < new Date(this.startY).getFullYear()) ||
              time.getFullYear() > currentYear;
        }
      },
      chartData: {
        years: [],
        costs: [],
        revenues: [],
        profits: []
      },
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.fetchData()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {

    //获取收益列表
    getRevenueList(){
      return getRevenueListApi(this.startY,this.endY).then(res =>{
        const startYear = parseInt(this.startY)
        const endYear = parseInt(this.endY)
        const yearCount = endYear - startYear + 1
        const revenueData = Array.isArray(res.data) ? res.data.map(Number): []
        // 如果数据不足，在头部补0
        if (revenueData.length < yearCount) {
          const zerosToAdd = yearCount - revenueData.length;
          this.chartData.revenues = [...Array(zerosToAdd).fill(0), ...revenueData];
        } else {
          this.chartData.revenues =revenueData.slice(0, yearCount);
        }
        // 确保长度正好等于yearCount
        this.chartData.revenues = this.chartData.revenues.slice(0, yearCount);
      })
    },
    //获取支出列表
    getCostList(){
      return getCostsListApi(this.startY,this.endY).then(res =>{
        const startYear = parseInt(this.startY)
        const endYear = parseInt(this.endY)
        const yearCount = endYear - startYear + 1
        const costsData = Array.isArray(res.data) ? res.data.map(Number): []
        // console.log(costsData)
        // 如果数据不足，在头部补0
        if (costsData.length < yearCount) {
          const zerosToAdd = yearCount - costsData.length;
          this.chartData.costs = [...Array(zerosToAdd).fill(0), ...costsData];
        } else {
          this.chartData.costs = costsData.slice(0, yearCount);
        }
        // 确保长度正好等于yearCount
        this.chartData.costs = this.chartData.costs.slice(0, yearCount);
      })
    },

    initChart() {
      this.chart = echarts.init(this.$refs.profitChart, 'macarons')
      this.updateChart()
    },

    async fetchData() {
      // console.log(this.startY+"  "+this.endY)
      try {
        const startYear = parseInt(this.startY)
        const endYear = parseInt(this.endY)
        const yearCount = endYear - startYear + 1

        this.chartData.years = Array.from({length: yearCount}, (_, i) => startYear + i + '年')
        // 确保costs数组存在且长度正确
        await this.getCostList()
        await this.getRevenueList()
        console.log(this.chartData.revenues)
        this.chartData.profits = this.chartData.revenues.map((rev, i) => rev - this.chartData.costs[i])

        this.updateChart()
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
      }
    },


    updateChart() {
      if (!this.chart) return

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            let result = params[0].axisValue + '<br/>'
            params.forEach(item => {
              result += `${item.marker} ${item.seriesName}: ${item.value.toLocaleString()}元<br/>`
            })
            return result
          }
        },
        legend: {
          data: ['总成本', '总收益', '总利润'],
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.chartData.years,
          axisLabel: {
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} 元'
          }
        },
        series: [
          {
            name: '总成本',
            type: 'line',
            data: this.chartData.costs,
            itemStyle: {
              color: '#FF6B6B'
            },
            lineStyle: {
              width: 3
            },
            symbolSize: 8,
            smooth: true
          },
          {
            name: '总收益',
            type: 'line',
            data: this.chartData.revenues,
            itemStyle: {
              color: '#4ECDC4'
            },
            lineStyle: {
              width: 3
            },
            symbolSize: 8,
            smooth: true
          },
          {
            name: '总利润',
            type: 'line',
            data: this.chartData.profits,
            itemStyle: {
              color: '#FFD166'
            },
            lineStyle: {
              width: 3
            },
            symbolSize: 8,
            smooth: true,
            markLine: {
              silent: true,
              data: [
                {
                  type: 'average',
                  name: '平均值'
                }
              ],
              lineStyle: {
                color: '#FFD166',
                type: 'dashed'
              }
            }
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ]
      }

      this.chart.setOption(option, true)
      window.addEventListener('resize', this.handleResize)
    },

    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  },
  created() {

  }
}
</script>

<style scoped>
.profit-chart-container {
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.year-selector {
  display: flex;
  align-items: center;
}

.year-selector span {
  margin-right: 10px;
  font-size: 14px;
  color: #666;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
}

.profit-chart {
  width: 100%;
  height: 100%;
}

@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .year-selector {
    margin-top: 10px;
    width: 100%;
  }

  .year-selector >>> .el-date-editor {
    width: 100%;
  }
}
</style>




